﻿using Application.Common.Interfaces;
using Common.Enums;
using Common.Hubs;
using Common.MessageTemplates;
using Common.Models;
using Common.Utils;
using Domain.Entities.Identity;
using MediatR;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Application.Features.Users.EventHandlers;


public class AssignRoleToUserEvent<T> : DomainEvent
{
    public AssignRoleToUserEvent(T entity)
    {
        Entity = entity;
    }

    public T Entity { get; }
}


public class AssignRoleToUserEventHandler : INotificationHandler<AssignRoleToUserEvent<HashSet<User>>>
{
    private readonly ILogger<AssignRoleToUserEventHandler> _logger;
    private readonly IServiceProvider _serviceProvider;
    private readonly IHubContext<SignalRHub> _hubContext;

    public AssignRoleToUserEventHandler(
        ILogger<AssignRoleToUserEventHandler> logger,
        IServiceProvider serviceProvider,
        IHubContext<SignalRHub> hubContext)
    {
        _logger = logger;
        _serviceProvider = serviceProvider;
        _hubContext = hubContext;
    }

    public Task Handle(AssignRoleToUserEvent<HashSet<User>> notification, CancellationToken cancellationToken)
    {
        using (var scope = _serviceProvider.CreateScope())
        {
            var _context = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
            if (!_context.Roles.Any()) return Task.CompletedTask;


            var receiveMessageUsers = notification.Entity.ToList();
            if (!receiveMessageUsers.Any()) return Task.CompletedTask;

            foreach (var user in receiveMessageUsers) 
            {
                Random random = new Random();
                SignalRMessageTemplate signalRMessageTemplate = new SignalRMessageTemplate()
                {
                    Id = random.Next(999999999),
                    MessageType = MessageType.UpdateUserRole,
                    Content = $"你的账号角色发生了变化",
                    Username = user.UserName!
                };
                _hubContext.Clients.User(user.Id.ToString()).SendAsync("ReceivePrivateMessage", signalRMessageTemplate.ToJson(true, true));
            }
        }
        return Task.CompletedTask;
    }
}